package com.java.base.exercise.aysn;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author RenPu
 * @Date 2023/5/10 11:42
 * @Version 1.0
 * @Description:
 **/
public class ThreadPoolUtils {
    private final Map<String, ExecutorService> threadPoolMap = new ConcurrentHashMap<>();

    /**
     * 获取线程池
     *
     * @param poolEnum 枚举类型
     * @return ExecutorService 线程池对象
     */
    public ExecutorService getThreadPool(ThreadPoolEnum poolEnum) {
        ExecutorService threadPool = threadPoolMap.get(poolEnum.getName());

        //此处使用DCL（DOUBLE CHECK LOCK）双重检查锁机制
        if (threadPool == null) {
            synchronized (this) {
                threadPool = threadPoolMap.get(poolEnum.getName());
                if (threadPool == null) {
                    threadPool = new ThreadPoolExecutor(
                            poolEnum.getCorePoolSize(),
                            poolEnum.getMaxPoolSize(),
                            60L,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(poolEnum.getQueueCapacity()),
                            new ThreadFactoryBuilder().setNameFormat(poolEnum.getName() + "-%d").build(),
                            new ThreadPoolExecutor.AbortPolicy()
                    );
                    threadPoolMap.put(poolEnum.getName(), threadPool);
                }
            }
        }
        return threadPool;
    }

    /**
     * 关闭线程池
     *
     * @param poolEnum 枚举类型
     */
    public void shutdown(ThreadPoolEnum poolEnum) {
        ExecutorService threadPool = threadPoolMap.remove(poolEnum.getName());
        if (threadPool != null) {
            threadPool.shutdown();
        }
    }

}
